/*
 * CommonUtility.cpp
 *
 *  Created on: Aug 15, 2011
 *      Author: mengwei.chua
 */

#include "CommonUtility.h"
#include "zlib/zlib.h"
#include "string.h"

namespace projectcos
{
namespace common
{

std::string CommonUtility::Base64Encode(const projectcos::common::Buffer<unsigned char>& data)
{
	std::string out;
	unsigned int size = data.GetSize();

	for(int i = 0; i < size; i += 3)
	{
		out += indexTable[((data[i] & 0xFC) >> 2)];

		if(i + 1 < size)
		{
			out += indexTable[(((data[i] & 0x03) << 4) | ((data[i+1] & 0xF0) >> 4))];

			if(i + 2 < size)
			{
				out += indexTable[(((data[i+1] & 0x0F) << 2) | ((data[i+2] & 0xC0) >> 6))];
				out += indexTable[(data[i+2] & 0x3F)];
			}
			else
			{
				out += indexTable[(char)((data[i+1] & 0x0F) << 2)];
				out += "=";
			}
		}
		else
		{
			out += indexTable[((data[i] & 0x03) << 4)];
			out += "==";
		}
	}

	return out;
}

void CommonUtility::Base64Decode(const std::string str, projectcos::common::Buffer<unsigned char>& data)
{
	std::string in = str;

	int index = in.find('=');
	while(std::string::npos != index)
	{
		in.erase(index, 1);
		index = in.find('=');
	}

	for(int i = 0 ; i < in.size(); ++i)
	{
		in[i] = (char)indexTable.find(in[i]);
	}

	index = 0;
	for(int i = 0; i < in.size(); i += 4)
	{
		// first byte
		data.Append((unsigned char)((in[i] << 2) | ((in[i+1] & 0x30) >> 4)));

		// second byte
		if(i + 2 < in.size())
		{
			data.Append((unsigned char)(((in[i+1] & 0x0F) << 4) | ((in[i+2] & 0x3C) >> 2)));
		}
		else
		{
			continue;
		}

		// third byte
		if(i + 3 < in.size())
		{
			data.Append((unsigned char)(((in[i+2] & 0x03) << 6) | in[i+3]));
		}
		else
		{
			continue;
		}
	}
}

#define CHUNK 16384

int CommonUtility::Compress(const projectcos::common::Buffer<unsigned char>& inData, projectcos::common::Buffer<unsigned char>& outData)
{
	int ret = 0, flush = 0;
    unsigned int have;
    z_stream strm;
    unsigned char in[CHUNK];
    unsigned char out[CHUNK];

	unsigned char const * inPtr = inData.GetData();
	unsigned int inIt = 0u;
	unsigned int inSize = inData.GetSize();

	/* allocate deflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    ret = deflateInit(&strm, Z_DEFAULT_COMPRESSION);
    if (ret != Z_OK)
	{
        return ret;
	}

	/* compress until end of file */
    do
	{
		if(inSize - inIt > CHUNK)
		{
			memcpy(in, inPtr+inIt, CHUNK);
			inIt += CHUNK;
			strm.avail_in = CHUNK;
		}
		else
		{
			memcpy(in, inPtr+inIt, inSize - inIt);
			strm.avail_in = inSize - inIt;
			inIt += inSize - inIt;
		}

		if (strm.avail_in == 0)
		{
            break;
		}

        strm.next_in = in;

		/* run deflate() on input until output buffer not full, finish
           compression if all of source has been read in */
        do
		{
			strm.avail_out = CHUNK;
            strm.next_out = out;

			ret = deflate(&strm, flush);    /* no bad return value */
            if(ret == Z_STREAM_ERROR)  /* state not clobbered */
			{
				(void)deflateEnd(&strm);
                return Z_ERRNO;
			}

			have = CHUNK - strm.avail_out;
			outData.Append(out, have);
		}
		while (strm.avail_out == 0);
		/* done when last data in file processed */
    } while (flush != Z_FINISH);

	/* clean up and return */
    (void)deflateEnd(&strm);
    return Z_OK;
}

int CommonUtility::Decompress(const projectcos::common::Buffer<unsigned char>& inData, projectcos::common::Buffer<unsigned char>& outData)
{
	int ret;
    unsigned have;
    z_stream strm;
    unsigned char in[CHUNK];
    unsigned char out[CHUNK];

	unsigned char const * inPtr = inData.GetData();
	unsigned int inIt = 0u;
	unsigned int inSize = inData.GetSize();

	/* allocate inflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.avail_in = 0;
    strm.next_in = Z_NULL;
    ret = inflateInit(&strm);
    if (ret != Z_OK)
	{
        return ret;
	}

	/* decompress until deflate stream ends or end of file */
    do
	{
		if(inSize - inIt > CHUNK)
		{
			memcpy(in, inPtr+inIt, CHUNK);
			inIt += CHUNK;
			strm.avail_in = CHUNK;
		}
		else
		{
			memcpy(in, inPtr+inIt, inSize - inIt);
			strm.avail_in = inSize - inIt;
			inIt += inSize - inIt;
		}

		if (strm.avail_in == 0)
		{
            break;
		}

        strm.next_in = in;

		/* run inflate() on input until output buffer not full */
        do
		{
			strm.avail_out = CHUNK;
            strm.next_out = out;

			ret = inflate(&strm, Z_NO_FLUSH);
            switch (ret)
			{
            case Z_NEED_DICT:
                ret = Z_DATA_ERROR;     /* and fall through */
            case Z_DATA_ERROR:
            case Z_MEM_ERROR:
                (void)inflateEnd(&strm);
                return ret;
            }

			have = CHUNK - strm.avail_out;
            outData.Append(out, have);
		}
		while (strm.avail_out == 0);
		/* done when inflate() says it's done */
    }
	while (ret != Z_STREAM_END);

	/* clean up and return */
    (void)inflateEnd(&strm);
    return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}

} // common
} // projectcos
